package com.jse;

import java.util.*;

/**
 * 简单的YAML解析工具类
 * 支持基本的YAML格式转换为Java Map和List
 */
public class Yaml {
    
    /**
     * 将YAML字符串解析为Map
     * @param yamlStr YAML格式的字符串
     * @return 解析后的Map对象
     */
    public static Map<String,Object> parseToMap(String yamlStr) {
        Map<String, Object> result = new LinkedHashMap<>();
        if (yamlStr == null || yamlStr.trim().isEmpty()) {
            return result;
        }

        String[] lines = yamlStr.split("\n");
        int currentIndent = 0;
        Stack<Map<String, Object>> mapStack = new Stack<>();
        Stack<String> keyStack = new Stack<>();
        mapStack.push(result);

        for (String line : lines) {
            if (line.trim().isEmpty() || line.trim().startsWith("#")) {
                continue;
            }

            // 计算当前行的缩进级别
            int indent = getIndentLevel(line);
            String trimmedLine = line.trim();

            // 处理缩进变化
            if (indent > currentIndent) {
                Map<String, Object> newMap = new LinkedHashMap<>();
                mapStack.peek().put(keyStack.peek(), newMap);
                mapStack.push(newMap);
            } else if (indent < currentIndent) {
                while (mapStack.size() > indent + 1) {
                    mapStack.pop();
                    keyStack.pop();
                }
            }
            currentIndent = indent;

            // 解析键值对
            if (trimmedLine.contains(":")) {
                String[] parts = trimmedLine.split(":", 2);
                String key = parts[0].trim();
                String value = parts.length > 1 ? parts[1].trim() : "";

                if (value.isEmpty()) {
                    // 可能是一个新的嵌套结构
                    keyStack.push(key);
                } else {
                    // 直接的键值对
                    mapStack.peek().put(key, parseValue(value));
                }
            }
        }

        return result;
    }

    /**
     * 将YAML字符串解析为List<Map>，每个一级键值对作为一个Map
     * @param yamlStr YAML格式的字符串
     * @return 解析后的List对象，每个元素是一个Map
     */
    public static List<Map<String, Object>> parseToList(String yamlStr) {
        List<Map<String, Object>> result = new ArrayList<>();
        if (yamlStr == null || yamlStr.trim().isEmpty()) {
            return result;
        }

        String[] lines = yamlStr.split("\n");
        Map<String, Object> currentMap = null;
        int currentIndent = 0;
        Stack<Map<String, Object>> mapStack = new Stack<>();
        Stack<String> keyStack = new Stack<>();

        for (String line : lines) {
            if (line.trim().isEmpty() || line.trim().startsWith("#")) {
                continue;
            }

            int indent = getIndentLevel(line);
            String trimmedLine = line.trim();

            // 处理一级键值对
            if (indent == 0) {
                if (currentMap != null) {
                    result.add(currentMap);
                }
                currentMap = new LinkedHashMap<>();
                mapStack.clear();
                keyStack.clear();
                mapStack.push(currentMap);
                currentIndent = 0;
            }
            // 处理缩进变化
            else if (indent > currentIndent) {
                Map<String, Object> newMap = new LinkedHashMap<>();
                mapStack.peek().put(keyStack.peek(), newMap);
                mapStack.push(newMap);
            } else if (indent < currentIndent) {
                while (mapStack.size() > indent + 1) {
                    mapStack.pop();
                    keyStack.pop();
                }
            }
            currentIndent = indent;

            // 解析键值对
            if (trimmedLine.contains(":")) {
                String[] parts = trimmedLine.split(":", 2);
                String key = parts[0].trim();
                String value = parts.length > 1 ? parts[1].trim() : "";

                if (value.isEmpty()) {
                    // 可能是一个新的嵌套结构
                    keyStack.push(key);
                } else {
                    // 直接的键值对
                    mapStack.peek().put(key, parseValue(value));
                }
            }
        }

        // 添加最后一个Map
        if (currentMap != null && !currentMap.isEmpty()) {
            result.add(currentMap);
        }

        return result;
    }

    /**
     * 解析YAML中的值
     * @param value 值字符串
     * @return 解析后的对象
     */
    private static Object parseValue(String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }

        // 移除引号
        if ((value.startsWith("\"") && value.endsWith("\"")) || 
            (value.startsWith("'") && value.endsWith("'"))) {
            return value.substring(1, value.length() - 1);
        }

        // 解析布尔值
        if (value.equalsIgnoreCase("true")) {
            return true;
        }
        if (value.equalsIgnoreCase("false")) {
            return false;
        }

        // 解析null
        if (value.equalsIgnoreCase("null") || value.equals("~")) {
            return null;
        }

        // 尝试解析数字
        try {
            if (value.contains(".")) {
                return Double.parseDouble(value);
            } else {
                return Long.parseLong(value);
            }
        } catch (NumberFormatException e) {
            // 不是数字，作为字符串处理
            return value;
        }
    }

    /**
     * 获取缩进级别
     * @param line 行字符串
     * @return 缩进级别
     */
    private static int getIndentLevel(String line) {
        int indent = 0;
        while (indent < line.length() && (line.charAt(indent) == ' ' || line.charAt(indent) == '\t')) {
            indent++;
        }
        return indent / 2; // 假设每级缩进是2个空格
    }
}